import React, {Component} from 'react';
import axios from 'axios';
import {List} from "antd";

import "./search.css"


class Search extends Component {

  state = {
    page: 1,
    count: 10,
    data: []
  };


  isLoading = false;

  componentWillMount() {
    console.log("componentWillMount");

    this.setState(this.props.location.state ? this.props.location.state : {});

    console.log(this.props.location.state ? this.props.location.state : {}, this.state);
  }

  componentDidMount() {
    console.log("componentDidMount");

    const {value, category, page} = this.state;
    if (!value || !category) return;

    this.getData(page)
  }

  render() {
    let data = this.state.data;
    return (
      <div>
        <List
          size="large"
          header={<div className="Center">GANK API</div>}
          footer={<div className="Center" onClick={(e) => this.loadMore()}>加载更多</div>}
          bordered
          dataSource={data}
          renderItem={item => (<List.Item onClick={e => this.handleClick(e, item)}>{item.desc}</List.Item>)}
        />
      </div>
    )
  }

  loadMore() {
    const page = this.state.page;
    this.getData(page + 1);
  }

  getData(page) {
    const {data, value, category, count} = this.state;
    if (this.isLoading) return;

    this.isLoading = true;

    axios.get('https://gank.io/api/search/query/' + value + '/category/' + category + '/count/' + count + '/page/' + page)
      .then(resp => {
        console.log(resp);

        let results = page === 1 ? resp.data.results : data.concat(resp.data.results);
        this.setState({
          page: page,
          data: results
        });

        this.isLoading = false;
      })
  }

  handleClick(e, item) {
    window.open(item.url);
  }
}

export default Search;
